
#include "../utils/Utility.hpp"
#include <iostream>
#include <filesystem>
#include <vector>
#include <unordered_map>
#include <algorithm>
#include <numeric>

// 获取相关项目对应的项目路径，用于admin进行配置
using namespace Extension;
namespace fs = std::filesystem;

std::string candidateList = "282";
std::string temp_am_login_evars_dir = "Y:\\temp\\AM_Login\\CMIH_EVARS";

std::vector<std::string> findMatchedProjectLines();
void createAdminLoginFile()
{
    auto lines = FileUtil::ReadAllLines("./evars.bat");
    // 对文件进行简单处理
    auto matchedLines = findMatchedProjectLines();
    if (matchedLines.size() == 0)
        return;

    std::for_each(matchedLines.cbegin(), matchedLines.cend(), [&](const std::string &item)
                  {
                    if (std::find(lines.cbegin(),lines.cend(),item) != lines.cend())
                    {   
                        //already exits, so we skip ....
                       std::cout <<"evars 已配置项目 =》 " <<item <<"\n";
                    }
                    else
                    {
                        std::cout <<"evars 文件末尾添加 =》 " <<item <<"\n";
                         lines.push_back(item); 
                    } });

    std::string content;
    std::for_each(lines.begin(), lines.end(), [&](const std::string &line)
                  { content = content + line + "\n"; });

    FileUtil::CreateFile("./evars.bat", content);
}

int main(int argc, char **argv)
{
    // 由于使用UTF-8 输入，而Windows控制台默认编码位GBK， 故先修改编码为UTF8
    system("chcp 65001");
    std::cout << "请输入需要配置的项目号 (输入q或quit退出): ";
    std::cin >> candidateList;

    if (candidateList == "q" || candidateList == "quit")
        return 0;

    createAdminLoginFile();

    // if (argc == 1)
    // {
    //     std::cout << "输入项目号，获取evar环境变量!";
    //     return 0;
    // }

    // candidateList = argv[1];
    system("admin160.bat");
    return 0;
}

std::vector<std::string> findMatchedProjectLines()
{
    std::vector<std::string> result;
    std::unordered_map<std::string, std::vector<std::string>> matchedCandiatesMap;
    try
    {
        for (const auto &entry : fs::recursive_directory_iterator(temp_am_login_evars_dir))
        {
            const auto &path = entry.path();
            if (entry.is_regular_file())
            {
                strncasecmp
                auto filename = path.filename().string();
                if (StringUtil::contains(filename, candidateList))
                {
                    // 读取文件内容获取evarshi 后台文件路径
                    auto text = FileUtil::ReadAllText(path.string());
                    auto pos = text.rfind(":eof");
                    auto setPos = text.find("set ", pos);
                    auto trimContext = text.substr(pos + 6, setPos - pos - 6);
                    auto lines = StringUtil::split(trimContext, "\r\n", [](std::string &text)
                                                   {
                                                       if (StringUtil::contains(text, candidateList))
                                                       {
                                                           return true;
                                                       }
                                                       return false; });

                    if (!StringUtil::contains(filename, "E3D"))
                        matchedCandiatesMap.try_emplace(filename, lines);
                    // for (auto &matchedItem : lines)
                    // {
                    //     printf(matchedItem.c_str());
                    //     printf("\n");
                    //     // TODO 直接加入到evars文件中
                    // }

                    // find the matched name
                    // return lines;
                }
            }
            else if (entry.is_directory())
            {
                // std::cout << "found directory: " << path << "\n";
            }
        }
    }
    catch (const std::exception &e)
    {
        std::cerr << "File system error" << e.what() << '\n';
    }

    if (matchedCandiatesMap.size() == 0)
    {
        std::cout << "未找到匹配的项目号";
        return result;
    }
    else if (matchedCandiatesMap.size() == 1)
    {
        auto iter = matchedCandiatesMap.begin();
        return iter->second;
    }
    else
    {
        std::string screenText = "存在多个符号的项目信息，项目列表如下\n";
        // 存在多个项目情况下进行有选择的配置
        int i = 0;
        for (auto const &entry : matchedCandiatesMap)
        {
            screenText += "\t" + std::to_string(++i) + " : " + entry.first + "\n";
        }
        screenText += "请输入需要配置的项目选项 (输入q或quit退出): ";
        std::cout << screenText;

        std::string input;
        std::cin >> input;

        if (input == "q" || input == "quit")
            return result;

        int selected = std::stoi(input);
        if (selected)
        {
            auto iter = matchedCandiatesMap.begin();
            while (--selected)
            {
                ++iter;
            };
            return iter->second;
        }
        else
        {
            std::cout << "选择对象不存在！\n";
        }
    }

    return result;
}